package com.demo.oauth2jFinalShiroClient.web;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import com.demo.oauth2jFinalShiroClient.config.HomeOAuth2Config;
import com.demo.oauth2jFinalShiroClient.config.OAuth2Config;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;

public class LoginController extends Controller {

	@ActionKey("/")
	public void index(){
		renderJsp("/index.jsp");
	}
	
	/**
	 * 跳转到第三方网站(认证服务器和资源服务器)进行登录授权
	 * @throws OAuthSystemException
	 * @author: jie.deng
	 */
	@ActionKey("thirdPartLogin")
	public void thirdPartLogin() throws OAuthSystemException {
		String channel = getPara("channel");
		if (HomeOAuth2Config.CONFIG_MAP.containsKey(channel)) {
			String state = UUID.randomUUID().toString();
			setSessionAttr(HomeOAuth2Config.OAUTH_STATE_SESSION_ATTR_NAME, state);	//state存在session中
			
			OAuth2Config config = HomeOAuth2Config.CONFIG_MAP.get(channel);
			HomeOAuth2Config.STATE_CONFIG_MAP.put(state, config, 3*60);	//state在180s内有效期，后续根据state确认回调来源
			
			OAuthClientRequest request = OAuthClientRequest
					.authorizationLocation(config.getServerAuthorizeUrl())
					.setClientId(config.getOauthClientId())
					.setRedirectURI(HomeOAuth2Config.CLIENT_CODE_CALLBACK_URL)
					.setResponseType(ResponseType.CODE.toString())
					.setState(state)
					.buildQueryMessage();		
			redirect(request.getLocationUri());
		}else {
			renderJsp("/index.jsp");
		}
	}

	/**
	 * 本站登录(GET|POST)
	 * @author: jie.deng
	 */
	@ActionKey("login")
	public void login() {
		HttpServletRequest req = getRequest();
		if (req.getMethod().equalsIgnoreCase("GET")) {
			renderJsp("/login.jsp");
		} else {
			//登录成功,直接跳转到默认页面或者登录之前的页面，不执行下面的代码
			//登录失败,执行下面的代码
			String className = String.valueOf(getAttr(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME));
			if (UnknownAccountException.class.getName().equals(className) || IncorrectCredentialsException.class.getName().endsWith(className)) {
				setAttr(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"用户名/密码错误");
			}else if (AuthenticationException.class.getName().endsWith(className)) {
				setAttr(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,"其他错误");
			}
			renderJsp("/login.jsp");
		}
	}

}
